function passgarp=garp(p,q)
% garp(p,q) tests GARP on the input parameters p and q
% It returns a value "passGARP" equal to 1 or 0.
% Make sure that p and q are Matlab TxN Matlab matrices,
% T = nr of observations and N = nr of goods.
% Preferrably use the script rungarp to make sure everything works OK.
% or at least use checkpqdata before running this function
%
% REQUIRES warshall
%
%GARP-website: http://www.revealedpreferences.org
%Aug 6, 2012

T=size(p,1);

% MAKE DRP-MATRIX AND P0-MATRIX
% DRP-matrix has T rows and columns. 
% Element (i,j)=1 if i DRP j (i directly revealed preferred over j)
DRP=eye(T);
P0=zeros(T,T);
for i=1:T
    for j=[1:i-1, i+1:T]
        if p(i,:)*q(i,:)'>=p(i,:)*q(j,:)'
            DRP(i,j)=1;
            if p(i,:)*q(i,:)'>p(i,:)*q(j,:)'
                P0(i,j)=1;
            end % if >
        end % if >=
    end % for j
end % for i

% MAKE RP-MATRIX (TRANSITIVE CLOSURE OF DRP-MATRIX) BY WARSHALL'S ALGORITHM
RP=warshall(DRP);

% SEARCH FOR GARP violations
passgarp=1;
for i=1:T
    for j=[1:i-1, i+1:T]
        if RP(i,j) && P0(j,i) % see GARP-definition
            passgarp=0; break
        end % if
    end % for j
    if ~passgarp, break, end
end % for i